package com.data2wisdom.comm.utils;

import java.io.UnsupportedEncodingException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 获取机器码
 * @author Jeffer
 *
 */
public class MachineCodeUtils {
	public static void main(String[] args) throws UnsupportedEncodingException, Exception {
//		List<String> list = getMAC(true);
//		if (list != null) {
//			for (String mac : list) {
//				System.out.println("MAC_S:" + mac);
//			}
//		}
		System.out.println(CpuIdUtil.getCPUId());
		System.out.println(MachineCodeUtils.getMachineCode());
	}
	
	
	/**
	 * 获取机器码
	 * @return
	 * @throws SocketException
	 */
	public static String getMachineCode() throws SocketException {
		String snCode = null;
		try {
			String cpuId = CpuIdUtil.getCPUId();
			
			if (cpuId != null){
				snCode = getMD5_16(cpuId.getBytes());
			}			
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
		
//		List<String> list = getMAC(true);
//		if (list != null) {
//			snCode = list.get(0);
//		}
		return snCode;
	}

	private static String getMD5_16(byte[] source) {
		String s = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest();
			char str[] = new char[8 * 2 + 3];
			int k = 0;
			for (int i = 0; i < 8; i++) {
				byte byte0 = tmp[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
				if ((i + 1) % 2 == 0 && i < 7)
					str[k++] = '-';
			}
			s = new String(str);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}

	public static List<String> getMAC(boolean isMD5_16) throws SocketException {
		List<String> mac_list = new ArrayList<String>();

		Enumeration<NetworkInterface> el;
		String mac_s = "";
		try {
			el = NetworkInterface.getNetworkInterfaces();
			while (el.hasMoreElements()) {
				byte[] mac = el.nextElement().getHardwareAddress();
				if (mac == null || mac.length == 0)
					continue;
				mac_s = hexByte(mac[0]) + "-" + hexByte(mac[1]) + "-" + hexByte(mac[2]) + "-" + hexByte(mac[3]) + "-"
						+ hexByte(mac[4]) + "-" + hexByte(mac[5]);
				if ("00-00-00-00-00-00".equals(mac_s))
					continue;

				if (isMD5_16) {
					mac_list.add(getMD5_16(mac_s.toUpperCase().getBytes()));
				} else {
					mac_list.add(mac_s.toUpperCase());
				}
			}
		} catch (SocketException e1) {
			throw e1;
		}
		return mac_list;
	}

	private static String hexByte(byte b) {
		String s = "000000" + Integer.toHexString(b);
		return s.substring(s.length() - 2);
	}
}
